package com.ruoyi.web.controller.common;

import cn.hutool.json.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.minio.PutObjectArgs;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

@RestController
public class UploadFile {
    @Autowired
    private MinioClient minioClient;
    // 需要定义bucketName常量或从配置中获取
    private String bucketName = "tjxt";

    @PostMapping("/minio/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {

            // 生成唯一的文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String minioId = UUID.randomUUID().toString() + fileExtension;
            // 上传文件到MinIO
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(minioId)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );
         JSONObject jsonObject = new JSONObject();
            jsonObject.set("code",0)
                    .set("data",
                            new JSONObject().set("fileId",minioId)
                                    .set("url","http://localhost:8001/dev-api/minio/"+minioId));

            return jsonObject.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传失败";
    }
    /**
     * 通过MinIO ID获取文件
     * @param minioId 文件在MinIO中的ID
     * @param response HTTP响应对象
     */
    @GetMapping("/minio/{minioId}")
    public void getFile(@PathVariable String minioId, HttpServletResponse response) {
        try (InputStream inputStream = minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(minioId)
                        .build())) {

            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + minioId + "\"");
            // 将文件流写入响应
            OutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
        } catch (MinioException e) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            e.printStackTrace();
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        }
    }
}
